<template>
  <section class="main">
    <a-card style="margin-top: 24px" :bordered="false" title="打卡计划">
      <template v-if="hasData">
        <a-row type="flex" justify="end">
          <a-col flex="2 2 auto">
            <p>
              {{ model.signInTemplateName
              }}<a-tag
                v-if="pausePlanEnable"
                :color="model.signInStatus == 1 ? 'pink' : 'grey'"
                style="margin-left: 20px;"
                >{{ model.signInStatusText }}</a-tag
              >
            </p>
            <p>起止时间：{{ model.signInStartdate }} - {{ model.signInEnddate }}</p>
          </a-col>
          <a-col flex="0 3 auto">
            <a-button
              type="danger"
              @click="handleChangeTemplate()"
              style="float: right; margin-right: 10px"
              >切换模板</a-button
            >
          </a-col>
          <a-col v-if="pausePlanEnable" flex="0 3 auto">
            <a-button
              type="danger"
              v-if="model.signInStatus == 1"
              @click="handleStopPlan(3)"
              style="float: right; margin-right: 10px"
              >暂停计划</a-button
            >
            <a-button
              type="danger"
              v-else-if="model.signInStatus == 3"
              @click="handleStopPlan(1)"
              style="float: right; margin-right: 10px"
              >恢复计划</a-button
            >
          </a-col>
        </a-row>
        <div
          style="margin-bottom: 15px;"
          class="ant-table ant-table-large ant-table-scroll-position-left ant-table-scroll-position-right"
        >
          <div class="ant-table-content">
            <div class="ant-table-scroll" style="overflow-x: auto;overflow-y:auto;height:500px">
              <!---->
              <div class="ant-table-body">
                <table class="">
                  <thead class="ant-table-thead" style="position:sticky;top:0;z-index:3">
                    <tr>
                      <th key="signInItem" class="" style="position:sticky;left:0">
                        <span class="ant-table-header-column" style="width: 120px">
                          <div>
                            <span class="ant-table-column-title">打卡项目</span
                            ><span class="ant-table-column-sorter"></span>
                          </div>
                        </span>
                      </th>
                      <th class="" v-for="day in weekItems" :key="day.id">
                        <span class="ant-table-header-column" style="width: 150px">
                          <div>
                            <span class="ant-table-column-title">
                              {{ day.title }}
                            </span>
                            <a-icon type="close" @click="cancelDay(day.id, day.title)" />
                            <span class="ant-table-column-sorter"></span>
                          </div>
                        </span>
                      </th>
                    </tr>
                  </thead>
                  <tbody class="ant-table-tbody" style="z-index:2">
                    <tr class="ant-table-row ant-table-row-level-0" v-for="(item, index) in clockInItems" :key="index">
                      <td class="" style="width: 13%;position:sticky;left:0;background:#fff">{{ item.title }}</td>
                      <td
                        class=""
                        v-for="(day, dindex) in weekItems"
                        :key="dindex"
                        @click.stop="modifyTime(item.title, day.id)"
                      >
                        <span style="cursor: pointer">{{ formatValue(item.title, day.id) }}</span>
                        <a-icon
                          v-if="formatValue(item.title, day.id) != ''"
                          type="close"
                          @click.stop="cancelTime(day.title, item.title, day.id)"
                        />
                      </td>
                      <!-- <td class="">{{ formatValue(item.title, 'signInJsonMonday') }} <a-icon v-if="formatValue(item.title, 'signInJsonMonday') != ''" type="close" @click="cancelTime('星期一', item.title, 'signInJsonMonday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonTuesday') }} <a-icon v-if="formatValue(item.title, 'signInJsonTuesday') != ''" type="close" @click="cancelTime('星期二', item.title, 'signInJsonTuesday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonWednesday') }} <a-icon v-if="formatValue(item.title, 'signInJsonWednesday') != ''" type="close" @click="cancelTime('星期三', item.title, 'signInJsonWednesday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonThursday') }} <a-icon v-if="formatValue(item.title, 'signInJsonThursday') != ''" type="close" @click="cancelTime('星期四', item.title, 'signInJsonThursday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonFriday') }} <a-icon v-if="formatValue(item.title, 'signInJsonFriday') != ''" type="close" @click="cancelTime('星期五', item.title, 'signInJsonFriday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonSaturday') }} <a-icon v-if="formatValue(item.title, 'signInJsonSaturday') != ''" type="close" @click="cancelTime('星期六', item.title, 'signInJsonSaturday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonSunday') }} <a-icon v-if="formatValue(item.title, 'signInJsonSunday') != ''" type="close" @click="cancelTime('星期日', item.title, 'signInJsonSunday')" /></td> -->
                    </tr>
                    <!-- <tr class="ant-table-row ant-table-row-level-0" data-row-key="1">
                      <td class="">测试打卡模板1</td>
                      <td class="">2022-01-11 14:12:35</td>
                      <td class="">张启壬</td>
                      <td
                        class="ant-table-fixed-columns-in-body ant-table-row-cell-break-word"
                        style="text-align: center"
                      >
                        <span data-v-3818d670=""
                          ><a data-v-3818d670="">编辑</a>
                          <div data-v-3818d670="" role="separator" class="ant-divider ant-divider-vertical"></div>
                          <a data-v-3818d670="" class="">删除</a></span
                        >
                      </td>
                    </tr> -->
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <a-row>
          <a-col :span="12" :offset="10">
            <a-button size="large" type="danger" @click="handleUpdatePlan" :loading="confirmLoading">保存</a-button>
          </a-col>
        </a-row>
      </template>
      <template v-else>
        该患者暂未设置打卡计划
      </template>
      <modify-time-modal ref="modifyTime" @modifyTime="handleModifyTime" />
      <modify-plan-modal ref="modifyPlanForm" @ok="handleModifyPlanOk" />
      <change-template-modal ref="ChangeTemplateForm" @ok="handleChangeTemplateOk" />
    </a-card>
  </section>
</template>

<script>
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import ModifyTimeModal from '@/views/clockIn/modules/ModifyTimeModal'
import ModifyPlanModal from './modules/ModifyPlanModal'
import ChangeTemplateModal from './modules/ChangeTemplateModal'
import moment from 'moment'
import { postAction, getAction } from '@/api/manage'

export default {
  name: 'ClockinPlan',
  components: {
    ModifyTimeModal,
    ModifyPlanModal,
    ChangeTemplateModal
  },
  data() {
    return {
      moment,
      weekItems: [
        {
          id: 'signInJsonMonday',
          title: '星期一'
        },
        {
          id: 'signInJsonTuesday',
          title: '星期二'
        },
        {
          id: 'signInJsonWednesday',
          title: '星期三'
        },
        {
          id: 'signInJsonThursday',
          title: '星期四'
        },
        {
          id: 'signInJsonFriday',
          title: '星期五'
        },
        {
          id: 'signInJsonSaturday',
          title: '星期六'
        },
        {
          id: 'signInJsonSunday',
          title: '星期日'
        }
      ],
      clockInItems: [
        {
          id: '1+1',
          title: '空腹血糖'
        },
        {
          id: '1+2',
          title: '早餐后血糖'
        },
        {
          id: '1+3',
          title: '午餐前血糖'
        },
        {
          id: '1+4',
          title: '午餐后血糖'
        },
        {
          id: '1+5',
          title: '晚餐前血糖'
        },
        {
          id: '1+6',
          title: '晚餐后血糖'
        },
        {
          id: '1+7',
          title: '睡前血糖'
        },
        {
          id: '1+8',
          title: '凌晨血糖'
        },
        {
          id: '5+1',
          title: '早餐饮食'
        },
        {
          id: '5+2',
          title: '午餐饮食'
        },
        {
          id: '5+3',
          title: '晚餐饮食'
        },
        {
          id: '3+0',
          title: '运动'
        },
        {
          id: '4+1',
          title: '早用药'
        },
        {
          id: '4+2',
          title: '午用药'
        },
        {
          id: '4+3',
          title: '晚用药'
        },
        {
          id: '4+4',
          title: '睡前用药'
        },
        {
          id: '9+1',
          title: '早胰岛素'
        },
        {
          id: '9+2',
          title: '午胰岛素'
        },
        {
          id: '9+3',
          title: '晚胰岛素'
        },
        {
          id: '9+4',
          title: '睡前胰岛素'
        },
        {
          id: '10+0',
          title: '睡眠'
        },
        {
          id: '11+1',
          title: '早营养素'
        },
        {
          id: '11+2',
          title: '午营养素'
        },
        {
          id: '11+3',
          title: '晚营养素'
        },
        {
          id: '11+4',
          title: '睡前营养素'
        },
        {
          id: '2+1',
          title: '早血压'
        },
        {
          id: '2+2',
          title: '晚血压'
        },
        {
          id: '8+0',
          title: '尿酮'
        },
        {
          id: '6+0',
          title: '体重'
        },
        {
          id: '7+0',
          title: '腰围'
        }
      ],
      model: {},
      pausePlanEnable: false,
      notify: false,
      hasData: false,
      confirmLoading: false
    }
  },
  mounted() {
    this.detail()
  },
  methods: {
    detail() {
      getAction('signin/plan/get', { patientId: this.$route.query[PAGE_MENU_TYPE.PatientId] }).then(res => {
        if (res.success) {
          this.weekItems.forEach(v => {
            if (
              !res.result[v.id].some(n => {
                if (n.item == '凌晨血糖') {
                  return true
                }
              })
            ) {
              res.result[v.id].push({
                endtime: '07:00',
                item: '凌晨血糖',
                item_id: '1+8',
                recordType: 1,
                starttime: '06:00',
                subType: 8
              })
            }
            if (
              !res.result[v.id].some(n => {
                if (n.item == '睡眠') {
                  return true
                }
              })
            ) {
              res.result[v.id].push({
                endtime: '10:00',
                item: '睡眠',
                item_id: '10+0',
                recordType: 10,
                starttime: '06:00',
                subType: 0
              })
            }
          })
          this.model = res.result
          this.hasData = res.success
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    formatValue(title, day) {
      if (this.model && this.model[day]) {
        let obj = this.model[day].find(function(value) {
          return value.item == title
        })

        if (obj?.starttime) {
          return obj?.starttime + ' - ' + obj?.endtime
        } else {
          return ''
        }
      } else {
        return ''
      }
    },
    cancelDay(day, title) {
      let that = this
      this.$confirm({
        title: '是否删除' + title + '的打卡时间?',
        onOk() {
          that.model[day].forEach((item, index) => {
            that.model[day][index].starttime = ''
            that.model[day][index].endtime = ''
            that.$set(that.model[day], index, that.model[day][index])
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    modifyTime(title, day) {
      const formatedValue = this.formatValue(title, day)
      if (formatedValue) {
        const obj = this.model[day].find(function(value) {
          return value.item == title
        })
        this.$refs.modifyTime.edit({ title, day }, JSON.parse(JSON.stringify(obj)))
        this.$refs.modifyTime.title = '修改时间'
      } else {
        this.$refs.modifyTime.edit({ title, day }, {})
        // this.$refs.modifyTime.visible = true
        this.$refs.modifyTime.title = '添加时间'
      }
    },
    cancelTime(week, title, day) {
      let that = this
      this.$confirm({
        title: '是否删除' + week + title + '打卡事件?',
        content: h => (
          <a-checkbox checked={that.notify} onChange={this.onChange}>
            同步每天此时间段
          </a-checkbox>
        ),
        onOk() {
          if (that.notify == true) {
            that.weekItems.forEach(item => {
              const index = that.model[item.id].findIndex(function(value) {
                return value.item == title
              })
              that.model[item.id][index].starttime = ''
              that.model[item.id][index].endtime = ''
              that.$set(that.model[item.id], index, that.model[item.id][index])
            })
          } else {
            const index = that.model[day].findIndex(function(value) {
              return value.item == title
            })
            that.model[day][index].starttime = ''
            that.model[day][index].endtime = ''
            that.$set(that.model[day], index, that.model[day][index])
          }
          that.notify = false
        },
        onCancel() {
          that.notify = false
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    onChange(e) {
      this.notify = e.target.checked
    },
    handleModifyTime(data) {
      console.log(data)
      let that = this
      if (data.notify == false) {
        const index = that.model[data.info.day].findIndex(function(value) {
          return value.item == data.info.title
        })
        that.model[data.info.day][index].starttime = data.data?.starttime.format('HH:mm')
        that.model[data.info.day][index].endtime = data.data?.endtime.format('HH:mm')
        that.$set(that.model[data.info.day], index, that.model[data.info.day][index])
      } else {
        that.weekItems.forEach(item => {
          const index = that.model[item.id].findIndex(function(value) {
            return value.item == data.info.title
          })
          that.model[item.id][index].starttime = data.data?.starttime.format('HH:mm')
          that.model[item.id][index].endtime = data.data?.endtime.format('HH:mm')
          that.$set(that.model[item.id], index, that.model[item.id][index])
        })
      }
    },
    handleUpdatePlan() {
      const that = this
      that.confirmLoading = true

      let model = JSON.parse(JSON.stringify(this.model))
      delete model.patientId
      delete model.signInTemplateId
      delete model.signInTemplateName
      delete model.signInStatus
      delete model.signInStatusText
      delete model.signInStartdate
      delete model.signInEnddate
      postAction('signin/plan/update', model)
        .then(res => {
          if (res.success) {
            that.$message.success(res.message)
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    handleStopPlan(status) {
      this.$refs.modifyPlanForm.edit({
        patientId: this.$route.query[PAGE_MENU_TYPE.PatientId],
        status: status,
        remark: ''
      })
      this.$refs.modifyPlanForm.title = status == 3 ? '暂停计划' : '恢复计划'
      // const that = this
      // this.$confirm({
      //   title: status == 3 ? '暂停计划' : '恢复计划',
      //   content: h => <a-textarea placeholder="Basic usage" rows={4} />,
      //   onOk() {
      //     postAction('signin/plan/status/change', { patientId: that.$route.query[PAGE_MENU_TYPE.PatientId], status: status}).then((res) => {
      //       if (res.success) {
      //         that.$message.success(res.message)
      //       } else {
      //         that.$message.warning(res.message)
      //       }
      //     })
      //   },
      //   onCancel() {
      //     console.log('Cancel');
      //   },
      //   class: 'test',
      // });
    },
    handleModifyPlanOk() {
      this.detail()
    },
    handleChangeTemplate() {
      this.$refs.ChangeTemplateForm.edit(this.model)
    },
    handleChangeTemplateOk() {
      this.detail()
    }
  }
}
</script>

<style lang="less" scoped>
.no-data {
  color: rgba(0, 0, 0, 0.25);
  text-align: center;
  line-height: 64px;
  font-size: 16px;

  i {
    font-size: 24px;
    margin-right: 16px;
    position: relative;
    top: 3px;
  }
}
.table-operator {
  margin-bottom: 10px;
}

.clName .ant-tree li span.ant-tree-switcher,
.ant-tree li span.ant-tree-iconEle {
  width: 10px !important;
}

.clName .ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
  background-color: #1890ff !important;
}
</style>

